package com.jet.chat.dbquery;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import com.jet.chat.exception.ChatExceptionCheckAuthSQLException;

public class ChatQueryCheckAuth extends ChatQueryAbstract {

	@Override
	protected ChatQueryResult main(Connection conn, ChatQueryParams chatQueryParams) throws Exception {
		String username = ((ChatQueryCheckAuthParams) chatQueryParams).getUsername();
		String password = ((ChatQueryCheckAuthParams) chatQueryParams).getPassword();
		
		int userId = 0;
		
		try {
			PreparedStatement ps = conn.prepareStatement("select id from users where username = ? and password = ?");
			ps.setString(1, username);
			ps.setString(2, password);
			ResultSet results = ps.executeQuery();
			while(results.next()) {
				userId = results.getInt(1);
			}
			results.close();
		} catch (SQLException e) {
			throw new ChatExceptionCheckAuthSQLException("ошибка при авторизации");
		}

		Properties properties = new Properties();
		properties.put("userId", userId);
		
		ArrayList<Properties> result = new ArrayList<Properties>();
		result.add(properties);

		return new ChatQueryCheckAuthResult(userId);
	}

}
